import React, { PureComponent } from 'react'
import { Form, Row, Col, Input, Button,Icon, Select, DatePicker } from 'antd'
import moment from 'moment'
import * as R from 'ramda'
// import store from '../../../index'
import { transferOption, isNotEmptyAndNil } from '@/utils/common'
import styles from './index.less'

// const { dispatch } = store // todo: dispatch
const { RangePicker } = DatePicker
const FormItem = Form.Item
const dateFormat = 'YYYY-MM-DD HH:mm:ss'

// @Form.create()
export default class PateoSearchNewFormExpand extends PureComponent {

  state = {
    expandForm: false,
  };

  handleSearch = e => {
    e.preventDefault()
    const { form: { validateFields }, fetchUrl, payloadUrl, saveFormValues, dateFormatList, dateFormatListNoTime, handleRangePicker } = this.props
    validateFields((err, fieldsValue) => {
      if (err) return

      for (let para in fieldsValue) {
        if (!fieldsValue[para] || !fieldsValue[para].toString().trim()) {
          fieldsValue[para] = undefined
        }
      }

      if (handleRangePicker) {
        const rangePicker = handleRangePicker(fieldsValue)
        if (isNotEmptyAndNil(rangePicker)) return
      }

      // dateFormatList:是用来格式化时间的
      if (dateFormatList) {
        dateFormatList.map(title => fieldsValue[title] ?
          (fieldsValue[title] = moment(fieldsValue[title]).format('YYYY-MM-DD HH:mm:ss')) : (fieldsValue[title] = undefined))
      }

      // dateFormatListNoTime:是用来格式化日期的
      if (dateFormatListNoTime) {
        dateFormatListNoTime.map(title => fieldsValue[title] ?
          (fieldsValue[title] = moment(fieldsValue[title]).format('YYYY-MM-DD')) : (fieldsValue[title] = undefined))
      }

      // saveFormValues:子组件向父组件传递表单的数据 和 dateFormatList 的顺序不可颠倒。
      if (saveFormValues) saveFormValues(fieldsValue)
      dispatch({
        type: fetchUrl,
        payload: payloadUrl ? Object.assign(payloadUrl, fieldsValue) : fieldsValue,
      })
    })
  }

  handleFormReset = () => {
    const { form, fetchUrl, payloadUrl, handleFormReset } = this.props
    form.resetFields()
    if (handleFormReset) { handleFormReset() }
    dispatch({
      type: fetchUrl,
      payload: payloadUrl || {},
    })
  }

  renderForm = () => {
    const { form: { getFieldDecorator }, searchItems = [],isExpand } = this.props
    const loopFormItems = data => data.map((item, i) => {
      if (!this.state.expandForm&&isExpand && i > 1) {
        return null;
      }
      const { title, key, type } = item
      switch (type) {
        case 'input': {
          const placeholder = `请输入${typeof (title) === 'string' ? title : ''}`
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem
                key={key}
                label={title}
              >
                {getFieldDecorator(key)(
                  <Input placeholder={placeholder} />,
                )}
              </FormItem>
            </Col>
          )
        }
        case 'select': {
          const { selectOptions, keyValue, onSelectChange, initialValue, cantClear } = item
          const options = { initialValue }
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem key={key} label={title}>
                {getFieldDecorator(key, { ...options })(
                  <Select
                    placeholder='请选择'
                    showSearch
                    optionFilterProp="children"
                    allowClear={!cantClear}
                    onChange={onSelectChange}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                  >
                    {transferOption(selectOptions, keyValue)}
                  </Select>,
                )}
              </FormItem>
            </Col>
          )
        }
        case 'datePicker': {
          const { nohmsFormat, noTimeSelect } = item
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem key={key} label={title}>
                {getFieldDecorator(key)(
                  <DatePicker
                    showTime={!noTimeSelect}
                    format={nohmsFormat ? nohmsFormat : dateFormat}
                    showToday
                    getCalendarContainer={trigger => trigger.parentNode}
                  />,
                )}
              </FormItem>
            </Col>
          )
        }
        case 'rangePicker': {
          // 这里不再推荐使用noTimeSelect,showTime,
          const { nohmsFormat, noTimeSelect, specialStyle, disabledDate, disabledTime, showTime, style } = item
          return (
            <Col md={specialStyle || 8} sm={24} key={key}>
              <FormItem key={key} label={title}>
                {getFieldDecorator(key)(
                  <RangePicker
                    style={style}
                    disabledDate={disabledDate}
                    disabledTime={disabledTime}
                    showTime={R.isNil(showTime) ? !noTimeSelect : showTime}
                    format={nohmsFormat ? nohmsFormat : dateFormat}
                    placeholder={['开始时间', '结束时间']}
                    ranges={{
                      '本周 ': [moment().startOf('weeks'), moment()],
                      '最近一周 ': [moment().add(-1, 'weeks'), moment()],
                      '本月 ': [moment().startOf('months'), moment()],
                      '最近一个月 ': [moment().add(-1, 'months'), moment()],
                    }}
                    getCalendarContainer={trigger => trigger.parentNode}
                  />,
                )}
              </FormItem>
            </Col>
          )
        }
        //这个是用来调整格式的
        case 'blank': {
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem key={key}>
              </FormItem>
            </Col>
          )
        }
      }
    })
    return loopFormItems(searchItems)
  }

  render() {
    const { searchItems = [],isExpand,searchSpan = 8} = this.props;
    const { expandForm } = this.state;
    const offset =
    isExpand ?
    (searchItems.length <= 2
      ? 16 - (searchItems.length % 3) * 8
      : expandForm
      ? 16 - (searchItems.length % 3) * 8
      : 0):16 - (searchItems.length % 3) * 8;
    return (
      <div className={styles.tableListForm}>
        <Form onSubmit={this.handleSearch} layout='inline'>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            {this.renderForm()}
            <Col span={searchSpan} offset={offset}>
              <span className={styles.expendButtons}>
                <Button type='primary' htmlType='submit'>查询</Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
                {
                  this.props.searchItems.length > 2&&this.props.isExpand ? (
                    <a
                      style={{ marginLeft: 8 }}
                      onClick={() => this.setState({ expandForm: !this.state.expandForm })}
                    >
                      {!this.state.expandForm ? <span>展开 <Icon type="down" /></span> : <span>收起 <Icon type="up" /></span>}
                    </a>
                  ) : null
                }
              </span>
            </Col>
          </Row>
        </Form>
      </div>
    )
  }
}

